package com.xinlang.excel.io;


import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.List;
import java.util.Map;

import com.xinlang.excel.RawTable;


/**
 * 以文本形式输出Table
 * 
 */
public class TextRawTableWriter<X, Y, Z> {

	PrintStream out = null;
	boolean shouldClose = false;

	// 构造方式之一: 直接输出至OutputStream
	public TextRawTableWriter(OutputStream out, String encode) throws IOException {
		this.out = new PrintStream(out, true, encode);
		this.shouldClose = false;
	}

	public TextRawTableWriter(OutputStream out) throws IOException {
		this(out, "UTF-8");
	}

	public TextRawTableWriter(PrintStream out) {
		this.out = out;
		this.shouldClose = false;
	}

	// 构造方式之一: 指定文件名
	public TextRawTableWriter(String filename) throws IOException {
		this(new FileOutputStream(filename), "UTF-8");
		this.shouldClose = true;
	}

	// 输出Table
	public void write(RawTable<X, Y, Z> table) throws IOException {
		if (table.getTitle() != null) {
			out.println(">>>>> " + table.getTitle() + " <<<<<");
		}
		// 输出
		//out.print("-");
		out.print(table.getRowName());
		for (Y y : table.getColumnList()) {
			out.print("\t");
			out.print(y);
		}
		out.println();
		List<X> rows = table.getRowKeyList();
		//for (Map.Entry<X, Map<Y, Z>> row : table.getRows().entrySet()) {
		for(X key: rows) {
			Map<Y, Z> row = table.getRow(key);
			//out.print(row.getKey());
			out.print(key);
			for (Y y : table.getColumnList()) {
				out.print("\t");
				Z value = row.get(y);
				if (value == null) {
					out.print("-");
				} else if (value instanceof Double) {
					out.print(value);
				} else if (value instanceof Integer) {
					out.print(value);
				} else {
					out.print(value);
				}
			}
			out.println();
		}
		out.flush();
	}

	public void close() {
		if (shouldClose && out != null) {
			out.close();
		}
		out = null;
	}

}
